var g_isSaved = false;

function getXmlHttp()
{
    var xmlhttp = null;
    try
    {
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch(e)
    {
        try
        {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch(e)
        {
            xmlhttp = false;
        }
    }
    if( (!xmlhttp) || (typeof(xmlHttp) == 'undefined') )
    {
        xmlhttp = new XMLHttpRequest();
    }
    return xmlhttp;
}

function changeState(elem, color, text)
{
    elem.style.display = 'inline';
    elem.style.color = color;
    elem.innerHTML = text;
}

function checkName(event)
{
    var req = getXmlHttp();
    var input = document.getElementById('input').value;
    var type = document.getElementById('type').innerHTML;
    var state = document.getElementById('state');
    var congratulations = document.getElementById('congratulations');
    req.onreadystatechange = function()
    {
        if( (req.readyState == 4) && (req.status == 200) )
        {
            if( (req.responseText == 'Already exist') || ( req.responseText == 'Invalid name') )
            {
                changeState(state, "red", req.responseText);
            }
            else
            {
                if(req.responseText == 'Available')
                {
                    changeState(state, "green", req.responseText);
                }
                else
                {
                    if ( !g_isSaved )
                    {
                        changeState(congratulations, "black", "Congratulations! You can edit your " + type + "! Follow this <a href=\"edit_quizz_content.php?name=" + req.responseText + "\">link</a>");
                        g_isSaved = true;
                    }
                }
            }
        }
    }
    if (event == 'blur')
    {
        req.open("GET", "check_name_uniqueness.php?name=" + input + "&type=" + type, true);
        req.send(null); 
    }                                                                                   
    if ( ( state.innerHTML == "Available" ) && ( event == 'click' ) && ( !g_isSaved ) )
    {
        req.open("GET", "save_quizz.php?name=" + input + "&type=" + type, true);
        req.send(null); 
    }

}

function initEvents(input, saveButton)
{
    if ( input.addEventListener )
    {
        input.addEventListener('keyup', function () { checkName('blur'); }, false);
        saveButton.addEventListener('click', function () { checkName('click'); }, false);
    }
    else if ( input.attachEvent )
    {
        input.attachEvent('onkeyup', function () { checkName('blur'); });
        saveButton.attachEvent('onclick', function () { checkName('click'); });
    }
}

window.onload = function()
{
    var input = document.getElementById('input');
    var saveButton = document.getElementById('saveButton');
    initEvents(input, saveButton);
}